package org.flower.web.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.flower.dao.ShoppingCartDao;
import org.flower.dao.UserDao;
import org.flower.dao.impl.ShoppingCartDaoImpl;
import org.flower.dao.impl.UserDaoImpl;
import org.flower.entity.User;

@WebServlet(urlPatterns="/userlogin.shtml")
public class loginServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {this.doPost(request, response);}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		//用户登录和注册
		String flag = request.getParameter("flag");//获取标识列
		String phone = request.getParameter("phone");//用户手机号
		UserDao udao = new UserDaoImpl(); 
		if(flag.equals("checkPhone")){
			//验证手机号是否可用
			if(udao.checkPhone(phone)){
				response.getWriter().print("手机号可用");
			}else{
				response.getWriter().print("手机号已注册");
			}
		}else if(flag.equals("zhuce")){
			//用户注册
			String pwd = request.getParameter("pwd");
			udao.userLogin(phone,pwd);
		}else if(flag.equals("login")){
			//用户登录
			String pwd = request.getParameter("pwd");
			//根据手机号和密码 验证是否可以登录
			User u = udao.login(phone, pwd);

			String href = "";

			if(u!=null){
				//用户登录成功  将用户保存到session中
				request.getSession().setAttribute("user",u);
				//将该用户的购物车数量保存到session中
				ShoppingCartDao shdao = new ShoppingCartDaoImpl();
				int num = shdao.getShoppingCountNum(u.getId());
				System.out.println(u.getId()+"号用户的购物车数量"+num);
				request.getSession().setAttribute("userShoppingCartNum",num);
				//跳转页面 返回true表示登录成功
				href = request.getContextPath()+"/index.shtml";
				response.getWriter().print(href);
			}else{
				response.getWriter().print(href);
			}
		}else if(flag.equals("tuiChu")){
			//用户退出登录
			//将保存到session的数据清空
			request.getSession().removeAttribute("user");
			//跳转页面 重定向
			response.sendRedirect(request.getContextPath()+"/index.shtml");
		}
		
	}

}
